package csu.web.mypetstore.domain;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class Captcha {
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int LENGTH = 6;
    private static final int WIDTH = 100;
    private static final int HEIGHT = 50;
    private static final Font FONT = new Font("Arial", Font.BOLD, 25);

    public static String generate() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

    public static BufferedImage generate(String captcha) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        // 设置背景颜色
        Color BACKGROUND_COLOR = Color.white;
        graphics.setColor(BACKGROUND_COLOR);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置字体和颜色
        graphics.setFont(FONT);
        graphics.setColor(Color.BLACK);

        // 绘制验证码字符串
        FontMetrics fontMetrics = graphics.getFontMetrics();
        int x = (WIDTH - fontMetrics.stringWidth(captcha)) / 2;
        int y = (HEIGHT - fontMetrics.getHeight()) / 2 + fontMetrics.getAscent();
        graphics.drawString(captcha, x, y);

        // 释放资源
        graphics.dispose();

        return image;
    }

}
